﻿using AutoMapper;
using DeviceController.Wpf.Common;
using DeviceController.Wpf.Core;
using DeviceController.Wpf.SaveInfoServices;
using DeviceController.Wpf.ViewModels;
using DeviceController.Wpf.ViewModels.UserManageViewModels;
using DeviceController.Wpf.Views;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Net;
using System.Windows;
using Workstation.ServiceModel.Ua;

namespace DeviceController.Wpf
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {

        private UaApplication _uaApp = null!;

        protected override void OnStartup(StartupEventArgs e)
        {
            var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DeviceController", "pki");

            _uaApp = new UaApplicationBuilder().
            SetApplicationUri($"urn:{Dns.GetHostName()}:DeviceController")
            .SetDirectoryStore(path)
            .Build();
            _uaApp.Run();

            base.OnStartup(e);
            var host = BuildHost();
            var view = host.Services.GetViewService<MainWindow, MainWindowViewModel>();
            this.MainWindow = view;
            view.Show();
        }

        /// <summary>
        /// 构建主机。
        /// </summary>
        private static IHost BuildHost()
        {
            var builder = Host.CreateDefaultBuilder();

            builder.ConfigureServices(services =>
            {
                services.AddTransient<MainWindow>();
                services.AddTransient<MainWindowViewModel>();
                services.AddTransient<TestWindow>();
                services.AddTransient<TestWindowViewModel>();
                services.AddTransient<ThicknessChartViewModel>();
                services.AddTransient<TemperatureChartViewModel>();
                services.AddTransient<CircleDataChartViewModel>();
                services.AddTransient<TargetTemperatureChartViewModel>();

                services.AddTransient<UserManageWindow>();
                services.AddTransient<UserManagerViewModel>();
                services.AddTransient<UserListViewModel>();
                services.AddTransient<UserRegisterViewModel>();

                // 这侧用户管理器。
                services.AddSingleton<UserManager>();
                // 注册存储服务。
                services.AddSingleton<ISaveInfoService, TypeSaveInfoService>();
                // 注册视图上下文。
                services.AddSingleton<ViewContext>();
                services.AddSingleton<IMapper, Mapper>();
                services.AddAutoMapper(typeof(ApplicationServiceProfile));
            });

            return builder.Build();
        }
    }
}
